<template>
  <a-modal
    :title="pop.title"
    :visible="visible"
    :maskClosable="false"
    :width="pop.width"
    @cancel="close"
    @ok="onPopSubmit"
    :confirmLoading="pop.loading"
  >
    <div class="ctr-box">
      <div class="skpz-search-address">
        <a-input-search
          placeholder="请输入地名"
          v-if="isStatus != 'view'"
          @search="onSearch"
          enterButton
          v-model="searchValue"
          allowClear
        />
        <div class="search-address-list" v-if="searchAddressList.length > 0 && searchListshow">
          <div
            class="search-address-name"
            v-for="(item, index) in searchAddressList"
            :key="index"
            @click="toMapAddress(item)"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <div style="position: absolute;left: 50%;top: 50%;z-index: 998;">
        <a-spin :spinning="searchLoading" tip="loading" size="large" />
      </div>
      <div style="display: flex;height: 60px;">
        <a-form layout="inline" :form="form" class="form-inline-vali">
          <a-form-item label="区域名称">
            <a-input
              :disabled="isStatus == 'view'"
              v-decorator="[
                'name',
                { initialValue: editForm.name, rules: [{ required: true, message: '区域名称不能为空！' }] }
              ]"
              placeholder="请输入区域名称"
            ></a-input>
          </a-form-item>
          <a-form-item label="区域类型">
            <j-dict-select-tag
              v-decorator="[
                'type',
                { initialValue: editForm.type, rules: [{ required: true, message: '区域类型不能为空！' }] }
              ]"
              :triggerChange="true"
              placeholder="请选择区域类型"
              style="width: 171px;"
              dictCode="area_type"
              :disabled="isStatus == 'view'"
            />
          </a-form-item>
        </a-form>
        <a-button
          type="danger"
          v-if="isStatus != 'view'"
          ghost
          class="r-clear"
          @click="removeOverlay"
        >清除已框选的区域</a-button
        >
      </div>
    </div>
    <Map ref="mapDrawId" :isToolShow="true" style="height: 550px; background-color: #f7f7f7;" />
  </a-modal>
</template>

<script>
import * as api from '@/api/xlgc/areaEvent.js'
import Map from '@/views/xlgc/modules/map'

export default {
  props: ['visible', 'row', 'isStatus', 'title', 'regionType'],
  components: {
    Map
  },
  data() {
    return {
      pop: {
        title: '地图框选',
        isShow: false,
        loading: false,
        width: 1150
      },
      form: this.$form.createForm(this),
      editForm: {},
      searchValue: '',
      searchAddressList: [],
      MarkerList: '',
      searchLoading: false,
      searchListshow: false
    }
  },
  computed: {},
  watch: {
    visible(value) {
      if (value) {
        this.form = this.$form.createForm(this)
        this.editForm = {
          chartVOList: []
        }
        this.pop.loading = false
        this.$nextTick(() => {
          this.removeOverlay()
          if (this.isStatus != 'add') {
            this.getDetail()
          }
        })
      }
    },
    title(value) {
      this.pop.title = value
    }
  },
  methods: {
    onClickRow(row) {
      let obj = {
        chartVOList: [
          {
            latitude: row.latitude,
            longtitude: row.longtitude,
            radius: row.radius
          }
        ]
      }
      this.$refs.mapDrawId.onChartVOList(obj)
    },
    onSearch() {
      // 搜索地址
      this.searchValue = this.searchValue.replace(/\s*/g, '')
      if (!this.searchValue) return false
      this.searchLoading = true
      // 参数：format=json&page_num=0&page_size=10&q=海口市&sq_type=bounds&bounds=19.754563,110.103888,20.123978,110.787787
      let params = { format: 'json', page_num: 0, page_size: 10, q: this.searchValue, sq_type: 'bounds' }
      api.getaddress(params).then(res => {
        this.searchLoading = false
        let str = res.data.replace(/\\/g, '')
        // console.log('str')
        // console.log(JSON.parse(str))
        let result = JSON.parse(str)
        // console.log(result)
        if (result.totalCount > 0) {
          this.searchAddressList = result.results
          if (this.searchAddressList.length == 1) {
            this.toMapAddress(this.searchAddressList[0])
            this.searchListshow = false
          } else {
            this.searchListshow = true
          }
        }
      })
    },
    close() {
      this.$emit('on-close')
      return false
    },
    getDetail() {
      this.searchLoading = true
      api
        .getDetailsById({ id: this.row.id })
        .then(res => {
          if (res.success) {
            this.searchLoading = false
            let { name, type, chartVOList } = res.result
            this.editForm = {
              name,
              type,
              chartVOList
            }
            this.$refs.mapDrawId.onChartVOList(this.editForm)
          }
        })
        .catch(e => {
          this.$message.warn('请求失败！')
        })
    },
    onPopSubmit() {
      if (this.isStatus == 'view') {
        this.close()
        this.pop.loading = false
      } else {
        this.form.validateFieldsAndScroll((err, values) => {
          if (!err) {
            this.editForm.chartVOList = this.$refs.mapDrawId.chartVOList // 获取框选区域
            if (this.editForm.chartVOList.length) {
              this.pop.loading = true
              this.editForm.regionType = this.regionType
              if (this.isStatus == 'edit') {
                this.editForm.id = this.row.id
                // 修改
                this.editForm.name = values.name
                this.editForm.type = values.type
                api
                  .updateByFrame(this.editForm)
                  .then(res => {
                    if (res.success) {
                      this.$message.success('修改成功！')
                      this.$emit('on-submit')
                      this.removeOverlay()
                      this.close()
                      this.pop.loading = false
                    } else {
                      this.pop.loading = false
                      this.$message.warning(res.message)
                    }
                  })
                  .catch(() => {
                    this.pop.loading = false
                    this.$forceUpdate()
                  })
              } else {
                // 添加
                let params = Object.assign(values, this.editForm)
                console.log('params', params)
                api
                  .createByFrame(params)
                  .then(res => {
                    if (res.success) {
                      this.$message.success('添加成功！')
                      this.$emit('on-submit')
                      this.removeOverlay()
                      this.close()
                      this.pop.loading = false
                    } else {
                      this.pop.loading = false
                      this.$message.warning(res.message)
                    }
                  })
                  .catch(() => {
                    this.pop.loading = false
                    this.$forceUpdate()
                  })
              }
            } else {
              this.$message.error(`请框选区域！`)
            }
          }
        })
      }
    },
    removeOverlay() {
      this.$refs.mapDrawId.clearAll()
      this.editForm.chartVOList = []
    }
  }
}
</script>
<style lang="less" scoped>
.ctr-box {
  // margin-bottom: 24px;
  .gutter-row {
    margin-bottom: 16px;
  }
  .r-clear {
    margin-top: 3px;
    // position: absolute;
    // right: 0;
    // margin-right: 30px;
    margin-left: 50px;
  }
}

.skpz-search-address {
  position: absolute;
  right: 27px;
  top: 147px;
  z-index: 999;
  width: 350px;
  .search-address-list {
    width: 302px;
    top: 38px;
    left: 0px;
    background-color: #fff;
    color: #aaa;
    font-size: 12px;
    height: 300px;
    overflow-y: scroll;
    .search-address-name {
      width: 100%;
      height: 30px;
      line-height: 30px;
      margin-left: 10px;
      border-bottom: 1px solid #d9d9d9;
      cursor: pointer;
    }
  }
}
/deep/.BMapLib_Drawing {
  // inset: 5px auto auto 5px !important;
  position: absolute !important;
  left: 5px !important;
  top: 5px !important;
}
.leftBox {
  overflow: hidden;
  position: absolute;
  left: 20px;
  top: 139px;
  height: 550px;
  width: 450px;
  .handle {
    position: absolute;
    display: inline-block;
    top: 0;
    z-index: 10;
    background: rgba(0, 0, 0, 0.6);
    height: 100%;
    cursor: pointer;
    transition: 0.5s;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .close-icon {
      font-size: 20px;
      color: #fff;
    }
    &.leftHandle {
      left: 0;
    }
    &.rightHandle {
      right: 0;
    }
  }
}
</style>
